const { userModel } = require('../models/user.model')
const { getToken } = require('../utils/jwt')



module.exports = (option = { required: true }) => {
    return async (ctx, next) => {
        if (!option.required) {
            //已经登录
            if (ctx.headers.authorization) { //客户端已经传入token了
                token = ctx.headers.authorization?.substr(7)
                id = getToken(token)
                user = await userModel.findById(id);
                if (!user) {
                    return ctx.body = { code: 401, msg: '没有这个用户' }
                } else {
                    ctx.user = user
                    ctx['token'] = id;
                    await next();
                }
            } else {
                await next();
            }
        } else {
            //必须验证token
            token = ctx.headers.authorization?.substr(7)
            id = getToken(token)
            if(!id){
                 return ctx.body = { code: 400, msg: '您还未登录，请先登录' }
            }
          
            user = await userModel.findById(id);
            if (!user) {
                return ctx.body = { code: 401, msg: '没有这个用户' }
            } else {
                ctx.user = user
                ctx['token'] = id;
                await next();
            }
        }
    }
}